package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.article.service.ArticleService;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;

@Service
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ArticleService articleService;
    @Override
    @Async
    public void buildArticleToMinIO(ApArticle apArticle, String content) {
//已知文章id
//        获取文章内容
        if(StringUtils.isNotBlank(content)){
            Template template=null;
            StringWriter out = new StringWriter();
            try {
//                文章通过freemaker生成html文件
                template = configuration.getTemplate("article.ftl");
//                数据模型
                HashMap<String, Object> map = new HashMap<>();
                map.put("content", JSONArray.parseArray(content));
//                合成
                template.process(map,out);
            } catch (Exception e) {
                e.printStackTrace();
            }
//            html上传至minio
            ByteArrayInputStream in = new ByteArrayInputStream(out.toString().getBytes());
            String path = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", in);
//            修改ap_article表，保存static——url字段
            articleService.update(Wrappers.<ApArticle>lambdaUpdate()
                    .eq(ApArticle::getId,apArticle.getId()).set(ApArticle::getStaticUrl,path));

        }

    }
}
